package com.taotao.rop.service;

import com.rop.annotation.HttpAction;
import com.rop.annotation.NeedInSessionType;
import com.rop.annotation.ServiceMethod;
import com.rop.annotation.ServiceMethodBean;
import com.taotao.admin.MyRopClient;
import com.taotao.admin.pojo.AnalyseUser;
import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.RopAppSecret;
import com.taotao.rop.database.domain.WechatUser;
import com.taotao.rop.database.domain.WechatUserAnalyse;
import com.taotao.rop.database.mapper.RopAppSecretMapper;
import com.taotao.rop.database.mapper.WechatUserAnalyseMapper;
import com.taotao.rop.database.mapper.WechatUserMapper;
import com.taotao.rop.response.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@ServiceMethodBean(httpAction = HttpAction.POST, version = "1.0")
public class WechatUserService {
    private SimpleDateFormat shortDF = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private WechatUserMapper userMapper;
    @Autowired
    private RopAppSecretMapper appSecretMapper;
    @Autowired
    private WechatUserAnalyseMapper userAnalyseMapper;

    @ServiceMethod(method = "wechatUser.insert", needInSession = NeedInSessionType.NO)
    public Object insertWechatUser(WechatUser request) {
        request.setStatus(Constant.STATUS_ENABLE);
        Integer id = userMapper.insertOne(request);

        BaseResponse<WechatUser> response = new BaseResponse<WechatUser>();
        if (id > 0) {
            response.setSuccess(true);
        }
        return response;
    }

    @ServiceMethod(method = "wechatUser.update", needInSession = NeedInSessionType.NO)
    public Object updateWechatUser(WechatUser request) {
        Integer id = userMapper.updateOne(request);
        if (id < 1) {
            //如果没有用户，则新增一条记录，为了统计旧粉丝取消关注
            request.setSubscribe_time(new Date().getTime());
            request.setStatus(Constant.STATUS_DISABLE);
            userMapper.insertOne(request);
        }

        BaseResponse<WechatUser> response = new BaseResponse<WechatUser>();
        if (id > 0) {
            response.setSuccess(true);
        }
        return response;
    }

    @ServiceMethod(method = "wechatUser.list")
    public Object getWechatUserByPage(WechatUser request) {
        List<WechatUser> respList = userMapper.getListByPage(request);

        BaseResponse<List<WechatUser>> response = new BaseResponse<List<WechatUser>>();
        response.setSuccess(true);
        response.setMsg("" + userMapper.getCount(request));
        response.setData(respList);
        return response;
    }

    @ServiceMethod(method = "wechatUser.analyseList")
    public Object getWechatUserAnalyseByPage(WechatUserAnalyse request) {
        List<WechatUserAnalyse> respList = userAnalyseMapper.getListByPage(request);

        BaseResponse<List<WechatUserAnalyse>> response = new BaseResponse<List<WechatUserAnalyse>>();
        response.setSuccess(true);
        response.setMsg("" + userAnalyseMapper.getCount(request));
        response.setData(respList);
        return response;
    }

    @ServiceMethod(method = "wechatUser.listAll", needInSession = NeedInSessionType.NO)
    public Object getWechatUser(WechatUser request) {
        List<WechatUser> respList = userMapper.getList(request);

        BaseResponse<List<WechatUser>> response = new BaseResponse<List<WechatUser>>();
        response.setSuccess(true);
        response.setData(respList);
        return response;
    }

    @ServiceMethod(method = "wechatUser.count")
    public Object countWechatuser(WechatUser request) {
        BaseResponse<Long> response = new BaseResponse<Long>();
        response.setSuccess(true);
        response.setData(userMapper.getCount(request));
        return response;
    }

    @ServiceMethod(method = "wechatUser.analyse")
    public Object analyseWechatuser(WechatUser request) {
        AnalyseUser analyseUser = getAnalyseUser(request.getAppId(), request.getStartTime(), request.getEndTime());
        analyseUser.setTitle(request.getTitle());

        BaseResponse<AnalyseUser> response = new BaseResponse<AnalyseUser>();
        response.setSuccess(true);
        response.setData(analyseUser);
        return response;
    }

    @Scheduled(cron = "0 0 2 * * ?")
    public synchronized void analyseUserCountDaily() throws ParseException {
        RopAppSecret condition = new RopAppSecret();
        condition.setStatus(Constant.STATUS_ENABLE);
        List<RopAppSecret> appSecretList = appSecretMapper.getList(condition);
        for (RopAppSecret appSecret : appSecretList) {
            Long endTime = shortDF.parse(shortDF.format(new Date())).getTime() - 1;
            Long startTime = endTime + 1 - 24 * 3600 * 1000L;
            AnalyseUser analyseUser;
            analyseUser = getAnalyseUser(appSecret.getAppId(), startTime, endTime);

            WechatUserAnalyse oneAnalyse = new WechatUserAnalyse();
            oneAnalyse.setTheDate(new Date(startTime));
            oneAnalyse.setAddCount(analyseUser.getAddCount());
            oneAnalyse.setCancelCount(analyseUser.getCancelCount());
            oneAnalyse.setFocusCount(analyseUser.getFocusCount());
            oneAnalyse.setAllFocusCount(analyseUser.getAllFocusCount());
            oneAnalyse.setAppId(appSecret.getAppId());
            oneAnalyse.setOldCount(analyseUser.getOldCount());
            oneAnalyse.setOldCancelCount(analyseUser.getOldCancelCount());
            oneAnalyse.setNewCancelCount(analyseUser.getNewCancelCount());
            oneAnalyse.setNewFocusCount(analyseUser.getNewFocusCount());

            WechatUserAnalyse insertOrNotCondition = new WechatUserAnalyse();
            insertOrNotCondition.setTheDate(oneAnalyse.getTheDate());
            insertOrNotCondition.setAppId(oneAnalyse.getAppId());
            List<WechatUserAnalyse> theList = userAnalyseMapper.getList(insertOrNotCondition);
            if (theList == null || theList.size() == 0) {
                userAnalyseMapper.insertOne(oneAnalyse);
            }
        }
    }

    private AnalyseUser getAnalyseUser(String appId, Long startTime, Long endTime) {
        AnalyseUser analyseUser = new AnalyseUser();

        WechatUser condition = new WechatUser();
        if (!MyRopClient.APP_ID.equalsIgnoreCase(appId)) {
            condition.setAppId(appId);
        }
        condition.setStatus(Constant.STATUS_ENABLE);
        /*condition.setEndTime(endTime);*/
        //到目前为止，本系统所有关注的
        int allFocusCount = userMapper.getUserCount(condition);

        condition.setStatus(Constant.STATUS_DISABLE);
        //到目前为止，原系统取消的
        int theCancel = userMapper.getUserCount(condition);

        //本系统所有关注的 + 原系统人数 - 原系统取消的 = 目前所有关注的
        RopAppSecret appSecretCondition = new RopAppSecret();
        if (!MyRopClient.APP_ID.equalsIgnoreCase(appId)) {
            appSecretCondition.setAppId(appId);
        }
        appSecretCondition.setStatus(Constant.STATUS_ENABLE);
        List<RopAppSecret> ropAppSecretList = appSecretMapper.getList(appSecretCondition);
        int oldCount = 0;
        for (RopAppSecret ropAppSecret : ropAppSecretList) {
            oldCount += ropAppSecret.getOldCount();
        }
        analyseUser.setAllFocusCount(allFocusCount + oldCount - theCancel);

        condition.setStartTime(startTime);
        condition.setEndTime(endTime);
        condition.setStatus(Constant.STATUS_ENABLE);
        //一段时间内所有关注的
        int addCount = userMapper.getUserCount(condition);
        analyseUser.setAddCount(addCount);

        //上报时原有用户总数
        analyseUser.setOldCount(oldCount);

        //一段时间内原有用户取消的
        condition.setStatus(Constant.STATUS_DISABLE);
        Integer oldCancelCount = userMapper.getUserCount(condition);
        analyseUser.setOldCancelCount(oldCancelCount);

        //一段时间内本系统用户取消的
        condition.setStatus(Constant.STATUS_DELETE);
        Integer newCancelCount = userMapper.getUserCount(condition);
        analyseUser.setNewCancelCount(newCancelCount);

        //一段时间内本系统净增用户数
        analyseUser.setNewFocusCount(addCount - newCancelCount);

        //一段时间内所有取消的
        int cancelCount = oldCancelCount + newCancelCount;
        analyseUser.setCancelCount(cancelCount);

        //一段时间内的净增长
        analyseUser.setFocusCount(addCount - cancelCount);

        return analyseUser;
    }
}
